//
//  BackgroundTask.swift
//
//  Created by Yaro on 8/27/16.
//  Copyright © 2016 Yaro. All rights reserved.
//

import AVFoundation

class BackgroundTask {
    
    // MARK: - Vars
    var player : AVAudioPlayer?
    var timer = Timer()
    var ca = 0
    // MARK: - Methods
    func startBackgroundTask() {
        NotificationCenter.default.addObserver(self, selector: #selector(interruptedAudio), name: AVAudioSession.interruptionNotification, object: AVAudioSession.sharedInstance())
        self.playAudio()
    }
    
    func stopBackgroundTask() {
        NotificationCenter.default.removeObserver(self, name: AVAudioSession.interruptionNotification, object: nil)
        player?.stop()
    }
    
    @objc fileprivate func interruptedAudio(_ notification: Notification) {
        if notification.name == AVAudioSession.interruptionNotification && notification.userInfo != nil {
            var info = notification.userInfo!
            var intValue = 0
            (info[AVAudioSessionInterruptionTypeKey]! as AnyObject).getValue(&intValue)
            if intValue == 1 { playAudio() }
        }
    }
    
    fileprivate func playAudio() {
        print("called")
        if ca==1
        {
            self.player?.prepareToPlay()

                     self.player?.play()
            return
        }
//        ca=1
        do {
            let bundle = Bundle.main.path(forResource: "coin-spin-light", ofType: "mp3")
            let alertSound = URL(fileURLWithPath: bundle!)
    try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.ambient)
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord, options: [.defaultToSpeaker,.allowBluetooth,.duckOthers,
                                                                                                        .allowBluetoothA2DP,.allowAirPlay])
           try AVAudioSession.sharedInstance().setActive(true)

            try self.player = AVAudioPlayer(contentsOf: alertSound)
            // Play audio forever by setting num of loops to -1
      self.player?.numberOfLoops = -1
        self.player?.volume = 0
     self.player?.prepareToPlay()

            self.player?.play()
            print("play")
        } catch { print(error) }
    }
}
